package system.task.tasks;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import system.entity.SysTaskJob;
import system.service.sys.SysTaskJobService;
import system.task.ExecutorContext;
import system.task.Task;
import system.task.TaskExecutor;
import system.task.TaskManager;
import system.task.config.TaskConfig;
import system.task.utils.TaskUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 任务加载任务
 */
@Slf4j
@Component
public class TaskLoadTask implements TaskExecutor {
    @Autowired
    private SysTaskJobService jobService;
    @Autowired
    private TaskManager taskManager;
    @Autowired
    private TaskConfig taskConfig;

    @Override
    public void run(ExecutorContext context) throws Exception {

        List<SysTaskJob> jobList = this.jobService.load(new SysTaskJob());
        if (jobList.size() == 0) {
            log.info("Task reload finish, find zero job");
            return;
        }

        //copy from cache
        jobList = new ArrayList<>(jobList);

        //remove expired
        //TaskUtil.removeExpires(jobList);

        //remove not start
        //function apply to trigger startTime and endTime
        //TaskUtil.notStart(jobList);

        log.info("Task reload finished, find " + jobList.size() + " jobs");

        //清理不存在的
        Set<String> nameSet = jobList.stream().map(item -> item.getName()).distinct().collect(Collectors.toSet());
        taskManager.cleanNoContain(nameSet);

        //添加新的
        for (SysTaskJob job : jobList) {
            Task task1 = new Task();
            BeanUtils.copyProperties(job, task1);
            taskManager.addTask(task1);
        }

    }
}
